package testGridTree;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import dao.DataBase;

/**
 * 数据库连接类.
 * connect me:419723443@qq.com
 */
public class GridTreeDao {
	private DataBase dao  = null;
	public GridTreeDao(){
		dao = new DataBase();
	}
	
	public int getFirstLevelCount(){
		int ans = 0;
		dao = new DataBase();
		ResultSet rs = dao.getResultSet("SELECT COUNT(1) FROM OM_DIS_T T WHERE  T.DIS_PARENT IS NULL");
		try {
			while(rs.next()){
				ans = rs.getInt(1);
			}
		} catch (Exception e) {
		}
		return ans;
	}	
	
	public List getList(int start,int end){
		List ans = new ArrayList();
		dao = new DataBase();
		String sql = "SELECT * FROM OM_DIS_T WHERE  DIS_PARENT  is NULL";
		sql = getRealQuerySql(sql,start-1,end-1);
		ResultSet rs = dao.getResultSet(sql);
		try {
			while(rs.next()){
				DisBean bean = new DisBean();
				bean.setDisid(rs.getString(1));
				bean.setDisname(rs.getString(2));
				bean.setDisparentId(notNull(rs.getString(3)));
				bean.setIsLeaf(isLeaf(bean.getDisid()));
				ans.add(bean);
			}
		} catch (Exception e) {
		}
		return ans;
	}
	
	public List getCommonList(int start,int end){
		List ans = new ArrayList();
		dao = new DataBase();
		String sql = "select * from om_dis_t t2 , (SELECT  dis_id FROM OM_DIS_T WHERE  DIS_PARENT  is NULL limit "+ (start-1) +","+(end-start)+") t1"+
				" where t2.dis_parent = t1.dis_id or t2.dis_id = t1.dis_id;";
		ResultSet rs = dao.getResultSet(sql);
		try {
			while(rs.next()){
				DisBean bean = new DisBean();
				bean.setDisid(rs.getString(1));
				bean.setDisname(rs.getString(2));
				bean.setDisparentId(notNull(rs.getString(3)));
				ans.add(bean);
			}
		} catch (Exception e) {
		}
		return ans;
	}
	
	public String getRealQuerySql(String queryStr,int start,int end){
		StringBuffer buf = new StringBuffer();
		buf.append(queryStr).append(" limit "+start+" ,"+(end-start));
		return buf.toString();
	}
	
	public String isLeaf(String id) {
		dao = new DataBase();
		ResultSet rs = dao
				.getResultSet("SELECT T.DIS_PARENT FROM OM_DIS_T T WHERE  T.DIS_PARENT ='"
						+ id + "'");
		try {
			while(rs.next()){
				return "1";
			}
		} catch (SQLException e) {			
		}
		return "0";
	}
	
	public List getListByParent(String parentId){
		List ans = new ArrayList();
		dao = new DataBase();
		ResultSet rs = dao.getResultSet("SELECT * FROM OM_DIS_T T WHERE  T.DIS_PARENT = '"+parentId+"'");
		try {
			while(rs.next()){
				DisBean bean = new DisBean();
				bean.setDisid(rs.getString(1));
				bean.setDisname(rs.getString(2));
				bean.setDisparentId(notNull(rs.getString(3)));
				bean.setIsLeaf(isLeaf(bean.getDisid()));
				ans.add(bean);
			}
		} catch (Exception e) {
		}
		return ans;
	}
	
	private String notNull(String str){
		if(str==null||"".equals(str.trim())){
			return "";
		}
		return str;
	}
}
